<template>
  <div class="app-container">
    <!-- 搜索查找功能 -->
    <div class="filter-container">
      <el-input v-model="listQuery.userId" placeholder="员工编号" clearable style="width: 160px;" class="filter-item"
        @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.username" placeholder="员工姓名" clearable style="width: 150px;" class="filter-item"
        @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.userIdCard" placeholder="身份证号" clearable style="width: 200px;" class="filter-item"
        @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.userDepartmentId" class="filter-item" clearable placeholder="部门"
        style="width: 180px;" @keyup.enter.native="handleFilter">
        <!-- 工件类目列表 options，字典数组，键值对格式-->
        <el-option v-for="item in options" :key="item.departmentId" :label="item.departmentName"
          :value="item.departmentId" />
      </el-select>
      <el-select v-model="listQuery.userStatus" placeholder="状态" clearable class="filter-item" style="width: 110px"
        @keyup.enter.native="handleFilter">
        <el-option v-for="item in statusOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.userRole" placeholder="角色" clearable class="filter-item" style="width: 110px"
        @keyup.enter.native="handleFilter">
        <el-option v-for="item in statusRoleOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button v-waves class="filter-item" type="success" icon="el-icon-circle-plus-outline" @click="handleAddUser">增加</el-button>
      <!-- 下载的功能实现 -->
      <!-- <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button> -->
    </div>

    <el-table v-loading="listLoading" :key="tableKey" :data="list" border fit highlight-current-row style="width: 100%;"
      @sort-change="sortChange">
      <el-table-column label="员工编号" prop="userId" sortable="custom" align="center" min-width="105px">
        <template slot-scope="scope">
          <span>{{ scope.row.userId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" min-width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="电话号码" min-width="115px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.userMobile }}</span>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" min-width="115px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.userEmail }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" min-width="50px">
        <template slot-scope="scope">
          <span>{{ scope.row.userSex | sexTypeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="身份证号" align="center" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.userIdCard }}</span>
        </template>
      </el-table-column>
      <el-table-column label="薪资/月" prop="userSalary" sortable="custom" align="center" min-width="105px">
        <template slot-scope="scope">
          <span>￥ {{ scope.row.userSalary }}</span>
        </template>
      </el-table-column>
      <el-table-column label="部门" align="center" min-width="105px">
        <template slot-scope="scope">
          <span>{{ departmentFilter(scope.row.userDepartmentId) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="角色" class-name="status-col" min-width="90px">
        <template slot-scope="scope">
          <span>{{ scope.row.userRole | roleTypeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="入职时间" prop="createdTime" sortable="custom" min-width="135px" align="center">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" min-width="90px">
        <template slot-scope="scope">
          <el-tag :type="scope.row.userStatus | statusFilter">{{ scope.row.userStatus | typeFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="100px" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getList" />

    <!-- 更新信息表单 -->
    <el-dialog :visible.sync="dialogFormVisible" title="修改员工信息">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px"
        style="width: 400px; margin-left:50px;">
        <el-form-item label="员工编号" prop="userId">
          <el-input v-model="temp.userId" :disabled="true" />
        </el-form-item>
        <el-form-item label="姓名" prop="username">
          <el-input v-model="temp.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="temp.password" />
        </el-form-item>
        <el-form-item label="联系电话" prop="userMobile">
          <el-input v-model="temp.userMobile" />
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input v-model="temp.userEmail" />
        </el-form-item>
        <el-form-item label="薪资/月" prop="userSalary">
          <el-input v-model.number="temp.userSalary" />
        </el-form-item>
        <el-form-item label="部门" prop="userDepartmentId">
          <el-select v-model="temp.userDepartmentId" class="filter-item" clearable style="width: 180px;">
            <el-option v-for="item in options" :key="item.departmentId" :label="item.departmentName"
            :value="item.departmentId" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="userRole">
          <el-select v-model="temp.userRole" placeholder="请选择" clearable>
            <el-option v-for="item in statusRoleOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="userStatus">
          <el-select v-model="temp.userStatus" placeholder="请选择" clearable>
            <el-option v-for="item in statusOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="updateData">确认</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 部门类别表单 -->
    <el-dialog v-if="true" :visible.sync="addDepartmentFormVisible" title="增加部门类别">
      <el-form ref="addDepartmentForm" :rules="rules" :model="mytemp" label-position="right" label-width="100px"
        style="width: 400px; margin-left:50px;">
        <!-- prop 和  v-model 必须保持一致-->
        <el-form-item label="部门类别" prop="departmentName">
          <el-input v-model="mytemp.departmentName" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDepartmentFormVisible = false">取消</el-button>
        <el-button type="primary" @click="addDepartment">确认</el-button>
      </div>
    </el-dialog>

    <!-- 新增信息表单 -->
    <el-dialog v-if="true" :visible.sync="addDialogFormVisible" title="增加员工">
      <el-form ref="addDataForm" :rules="rules" :model="temp" label-position="left" label-width="100px"
        style="width: 400px; margin-left:50px;">
      <el-form-item label="姓名" prop="username">
        <el-input v-model="temp.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="temp.password" />
      </el-form-item>
      <el-form-item label="性别" prop="userSexName">
        <el-radio-group v-model="temp.userSexName">
          <el-radio label="男"/>
          <el-radio label="女"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="身份证号" prop="userIdCard">
        <el-input v-model="temp.userIdCard" />
      </el-form-item>
      <el-form-item label="联系电话" prop="userMobile">
        <el-input v-model="temp.userMobile" />
      </el-form-item>
      <el-form-item label="邮箱" prop="userEmail">
        <el-input v-model="temp.userEmail" />
      </el-form-item>
      <el-form-item label="薪资/月" prop="userSalary">
        <el-input v-model.number="temp.userSalary" />
      </el-form-item>
      <el-form-item label="部门" prop="userDepartmentId">
        <el-select v-model="temp.userDepartmentId" class="filter-item" clearable style="width: 180px;">
          <el-option v-for="item in options" :key="item.departmentId" :label="item.departmentName"
            :value="item.departmentId" />
        </el-select>
        <!-- 增加添加部门类别功能 -->
        <el-button type="success" icon="el-icon-circle-plus-outline" @click="handleAddDepartment">增加</el-button>
      </el-form-item>
      <el-form-item label="角色" prop="userRole">
        <el-select v-model="temp.userRole" placeholder="请选择" clearable>
          <el-option v-for="item in statusRoleOptions" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="userStatus">
        <el-select v-model="temp.userStatus" placeholder="请选择" clearable>
          <el-option v-for="item in statusOptions" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="addDialogFormVisible = false">取消</el-button>
      <el-button type="primary" @click="addUser">确认</el-button>
    </div>

    </el-dialog>

  </div>
</template>


<script>
  import waves from '@/directive/waves'            // Waves directive
  import { parseTime } from '@/utils'
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
  import { fetchDepartmentSeries } from '@/api/init'
  import { fetchList, updateUser, addUser, addDepartment } from '@/api/system_users'
  import {} from '@/vendor/Export2Excel'

  const statusOptions = [
    { key: 0, display_name: '禁止' },
    { key: 1, display_name: '在职' }
  ]
  const statusRoleOptions = [
    { key: 0, display_name: '普通用户' },
    { key: 1, display_name: '管理员' }
  ]

  const statusSexOptions = [
    { key: 0, display_name: '女' },
    { key: 1, display_name: '男' }
  ]

  const calendarTypeKeyValue = statusOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  const calendarTypeKeyValueRole = statusRoleOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  const calendarTypeKeyValueSex = statusSexOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  export default {
    components: { Pagination },
    directives: {
      waves
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          0: 'danger',
          1: 'success',
          3: 'info'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      },
      sexTypeFilter(type) {
        return calendarTypeKeyValueSex[type]
      },
      roleTypeFilter(type) {
        return calendarTypeKeyValueRole[type]
      }
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 5,
          userId: undefined,
          username: undefined,
          userIdCard: undefined,
          userStatus: undefined,
          userDepartmentId: undefined,
          userRole: undefined,
          orderBy: undefined
        },
        statusOptions,
        statusRoleOptions,
        statusSexOptions,
        temp: {
          userId: undefined,
          username: undefined,
          password: undefined,
          userSex: undefined,
          userImg: undefined,
          userIdCard: undefined,
          userSalary: undefined,
          userMobile: undefined,
          userEmail: undefined,
          userStatus: undefined,
          userDepartmentId: undefined,
          userRole: undefined,
          createdTime: undefined,
          updatedTime: undefined,

          userSexName:undefined
        },
        mytemp: {
          departmentName: ""
        },
        dialogFormVisible: false,
        addDialogFormVisible: false,
        addDepartmentFormVisible: false,
        options: [],
        rules: {
          username: [
            { required: true, message: '请输入员工姓名' }
          ],
          password: [
            { required: true, message: '请输入登录密码', trigger: 'blur' }
          ],
          userMobile: [
            { required: true, message: '请输入电话号码', trigger: 'blur' }
          ],
          userEmail: [
            { required: true, message: '请输入邮箱', trigger: 'blur' }
          ],
          userSalary: [
            { required: true, message: '请输入员工薪水', trigger: 'blur' },
            { type: 'number', message: '售价必须为数字值' }
          ],
          userRole: [
            { required: true, message: '请输入员工角色', trigger: 'blur' }
          ],
          userDepartmentId: [
            { required: true, message: '请输入所属部门', trigger: 'blur' }
          ],
          userStatus: [
            { required: true, message: '请输入员工状态', trigger: 'blur' }
          ],
          departmentName: [
            { required: true, message: '请输入部门名称', trigger: 'blur' }
          ],
          userSexName: [
            { required: true, trigger: 'blur' }
          ],
          userIdCard: [
            { required: true, message: '请输入身份证号码', trigger: 'blur' }
          ],
        },
        downloadLoading: false
      }
    },
    created() {
      this.getList()
      this.getCategoryOpt()
    },
    methods: {
      getCategoryOpt() {
        fetchDepartmentSeries().then(response => {
          this.options = response.data.data
        })
      },
      // checkPermission,
      getList() {
        this.listLoading = true
        fetchList(this.listQuery).then(response => {
          if (response.data.code == 10000) {
            this.list = response.data.data.items
            this.total = response.data.data.total
          } else {
            this.$message({
              message: response.data.message,
              type: 'error'
            })
          }
          this.listLoading = false
        })
      },
      departmentFilter(department) {
        for (const v of this.options) {
          if (v.departmentId == department) {
            return v.departmentName
          }
        }
        return undefined
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleAddUser() {
        this.temp = Object.assign({}, {})
        this.addDialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['addDataForm'].clearValidate()
        })
      },
      handleAddDepartment() {
        this.mytemp.departmentName = null
        this.addDepartmentFormVisible = true
        this.$nextTick(() => {
          this.$refs['addDepartmentForm'].clearValidate()
        })
      },

      addDepartment() {
        // this.$refs['addCategoryForm'].validate((valid) => {window.console.log()})
        // 获取表单对象，验证 rules 得到验证的值 valid 为 true 或者 false
        this.$refs['addDepartmentForm'].validate((valid) => {
          // 验证通过
          if (valid) {
            // 做安全性校验
            var flag = true
            // 去掉字符串内的所有空格
            // this.temp.workpieceCategory = this.temp.workpieceCategory.replace(/\s*/g, '')
            // 判断工件类别是否已经被注册过
            // for (const v of this.options) {
            //   // 找到当前品牌的索引
            //   if (v.categoryName == this.mytemp.workpieceCategory) {
            //     flag = false
            //   } else {
            //     flag = true
            //   }
            // }

            if (flag) {
              addDepartment(this.mytemp).then(response => {
                if (response.data.code === 10000) {
                  this.getCategoryOpt()
                  this.$notify({
                    title: '成功',
                    message: response.data.message,
                    type: 'success',
                    duration: 2000
                  })
                } else {
                  this.$notify({
                    title: '错误',
                    message: response.data.message,
                    type: 'error',
                    duration: 2000
                  })
                }
                this.addCategoryFormVisible = false
              })
            } else {
              this.$notify({
                title: '错误',
                message: '该工件类别已经被注册',
                type: 'error',
                duration: 2000
              })
            }
            this.addDepartmentFormVisible = false
          }
        })

      },
      addUser() {
        this.$refs['addDataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            if(tempData.userSexName == '男'){
              tempData.userSex = 1
            }else{
              tempData.userSex = 0
            }
            tempData.userImg = '001.jpg'
            window.console.log(tempData)
            addUser(tempData).then(response => {
              if (response.data.code === 10000) {
                this.listQuery.orderBy = "createdTime desc"
                this.getList()
                this.$notify({
                  title: '成功',
                  message: response.data.message,
                  type: 'success',
                  duration: 2000
                })
              } else {
                this.$notify({
                  title: '错误',
                  message: response.data.message,
                  type: 'error',
                  duration: 2000
                })
              }
              this.addDialogFormVisible = false
            })
          }
        })
      },
      sortChange(data) {

        const { prop, order } = data
        if (order === 'ascending') {
          this.listQuery.orderBy = prop + ' asc'

        } else if (order === 'descending') {
          this.listQuery.orderBy = prop + ' desc'
        } else {
          this.listQuery.orderBy = null
        }
        window.console.log(this.listQuery.orderBy)
        this.handleFilter()
      },
      handleUpdate(row) {
        this.dialogFormVisible = true
        this.temp = Object.assign({}, row)
        this.temp.password = undefined
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      parseTime,
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            updateUser(tempData).then(response => {
              if (response.data.code === 10000) {
                this.getList()
                this.$notify({
                  title: '成功',
                  message: '更新成功',
                  type: 'success',
                  duration: 2000
                })
              } else {
                this.$notify({
                  title: '错误',
                  message: response.data.message,
                  type: 'error',
                  duration: 2000
                })
              }
              this.dialogFormVisible = false
            })
          }
        })
      },
    }
  }
</script>